// 数据包后面添加标记符号，然后在前面添加长度
package wirepack

import (
	"bytes"
)

const DELIMITER = "\n"
const LINEPACK = "line"

type Line struct {
	buf []byte
}

func NewLinePkt() *Line {
	return &Line{
		buf: make([]byte, 0),
	}
}

func (p *Line) Protocol() string {
	return LINEPACK
}

func (p *Line) Pack(buf []byte) []byte {
	return ByteSliceCombine(buf, []byte(DELIMITER))
}

// 解数据包
func (p *Line) Decode(data []byte) [][]byte {
	lines := make([][]byte, 0)
	p.buf = ByteSliceCombine(p.buf, data)
	for {
		index := bytes.Index(p.buf, []byte(DELIMITER))
		if index == -1 {
			break
		}
		lines = append(lines, p.buf[:index])
		p.buf = p.buf[index+len(DELIMITER):]
	}
	return lines
}
